/**
 *
 * websocket端口
 */
const port = 6688;

/**
 *
 * 主机地址
 */
const host = "127.0.0.1";

/**
 *
 * websocket url地址
 */
const url = "ws://" +host+ ":" + port;

/**
 * ping 消息类型
 */
const MSG_TYPE_PING = 2;
/**
 * 正常的接收的 消息类型
 */
const MSG_TYPE_NORMAL = 1;

let socket;
let userIdItem = "current_user_id";
let userId;
function connect(currentUserId){
    userId = currentUserId;
    socket = new WebSocket(url);
    socket.binaryType = 'arraybuffer';

    socket.onopen = function (e){
        console.log("连接成功了。。。")
        if (userId == null || undefined == userId || "" == userId){
            console.log("用户id为空，不绑定用户")
        }else{
            bind(userId);
        }

    }
    socket.onmessage =  function (e){


        if ( ! e.data instanceof ArrayBuffer){
            console.log("消息类型不正确，不处理")
            return;
        }
        let data = new Uint8Array(e.data);
        // 消息类型
        let type = data[0];
        if(MSG_TYPE_PING == type){
            // 服务端给客户端的心跳
            pong(userId);
        }
        if (MSG_TYPE_NORMAL == type){
            // 正常的消息类型
            // 前一位 是消息类型, 所以截取一下
            let body = data.subarray(1, data.length);
            let message = proto.Message.deserializeBinary(body);
            console.log("来消息了:"+message)

            var msg = "from:"+message.getFrom()+"; content:"+message.getContent();
            appendMsg(msg);
        }


    }
    socket.onclose = function (e){
        console.log("连接关闭了。。。")
    }
    return socket;
}

function generateUUID() {
    let d = new Date().getTime();
    let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        let r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid.replace(/-/g, '');
}

function pong(userId){

    let requestBody = new proto.RequestBody();
    requestBody.setUserid(userId);
    requestBody.setOptype("pong");
    requestBody.setTimestamp(new Date().getTime());
    if (webSocket.readyState != webSocket.OPEN){
        alert("通道被关闭了，请刷新页面");
        return;
    }
    console.log("处理客户端回复心跳事件："+JSON.stringify(requestBody));


    let data = requestBody.serializeBinary();
    let protobuf = new Uint8Array(data.length);
    protobuf.set(data, 0);
    webSocket.send(protobuf);

}
